package com.yhb.androidcore.network.http;

import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by yanghongbing on 16/12/31.
 */

public class HttpCallbackImpl implements Callback {

    private IDataCallback callback;

    public HttpCallbackImpl(IDataCallback callback) {
        this.callback = callback;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        Request okRequest = call.request();
        IRequest request = (IRequest) okRequest.tag();
        Log.d(HttpConsts.TAG, "--------onFailure " + request.getRequestId() + "--------");
        Log.d(HttpConsts.TAG, e.getMessage());
        Log.d(HttpConsts.TAG, "--------request " + request.getRequestId() + " end--------");
        if (callback != null) {
            boolean result = callback.onDataError(request, null);
            if (!result) {
                //TODO: 公共处理网络请求返回失败
            }
        }
    }

    @Override
    public void onResponse(Call call, Response okResponse) throws IOException {
        Request okRequest = okResponse.request();
        IRequest request = (IRequest) okRequest.tag();
        String responseString = okResponse.body().string();
        Log.d(HttpConsts.TAG, "--------onResponse " + request.getRequestId() + "--------");
        Log.d(HttpConsts.TAG, "response info : \n" + responseString);
        Log.d(HttpConsts.TAG, "--------request " + request.getRequestId() + " end--------");
        IResponse response = new HttpResponse();
        response.setCode(okResponse.code());
        response.setMessage(responseString);
        response.setSendRequestAtMillis(okResponse.sentRequestAtMillis());
        response.setReceivedResponseAtMillis(okResponse.receivedResponseAtMillis());
        if (okResponse.code() == 200) {
            if (callback != null) {
                callback.onDataReceived(request, response);
            }
        } else {
            if (callback != null) {
                callback.onDataError(request, response);
            }
        }
    }
}
